package davel

import (
	red "github.com/gomodule/redigo/redis"
	"time"
)

func newDavelRedis(config DavelRedisConfig) *DavelRedis {
	davelRedis := &DavelRedis{config: config}
	davelRedis.pool = &red.Pool{
		MaxIdle:    davelRedis.config.MaxIdle ,
		MaxActive:   0,
		IdleTimeout: time.Duration(davelRedis.config.IdleTimeout),
		Dial: func() (red.Conn, error) {
			return red.Dial(
				"tcp",
				davelRedis.config.Conn,
				red.DialReadTimeout(time.Duration(1000)*time.Millisecond),
				red.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
				red.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
				red.DialDatabase(davelRedis.config.DbNum),
				red.DialPassword(davelRedis.config.Password),
			)
		},
	}
	return davelRedis
}

type DavelRedisConfig struct {
	Key string //缓存名称
	Conn string //连接地址
	Password string //密码
	DbNum int //dbNum
	MaxIdle int //最大空闲
	IdleTimeout int //超时时间
}

type DavelRedis struct {
	pool     *red.Pool
	config   DavelRedisConfig
}

func(this *DavelRedis) Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
	con := this.pool.Get()
	if err := con.Err(); err != nil {
		return nil, err
	}
	defer con.Close()

	params := ArrayUnshift(key,args)
	return con.Do(cmd, params...)
}


func(this *DavelRedis) Gc() {
	this.pool.Close()
}